import KoaRouter from 'koa-router'
import { Models } from '@/common/typings/modle'

import Config from '@/config/Config'

import validator from '@/middlewares/validator'
import schema from '@/common/api-json-schema/system/auth/resetPassword'
import { command } from '@/server/mysql'
import { Account } from '@/common/typings/account'
import { HttpException, ParameterException, Success } from '@/core/HttpException'

const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/auth`,
})

router.post('/resetPassword', validator(schema, 'body'), async (ctx: Models.Ctx) => {
  const { password, email, phoneNumber } = ctx.request.body as any
  let res: Account.User[]
  if (email) {
    // 根据email 查询账号
    res = (await command(`SELECT * FROM system_user WHERE email = '${email}';`)).results
  } else if (phoneNumber) {
    // 根据手机号查询账号
    res = (await command(`SELECT * FROM system_user WHERE mobile = '${phoneNumber}';`)).results
  } else {
    throw new ParameterException()
  }
  if (res.length === 1) {
    const user = res[0]
    await command(`UPDATE system_user SET password = '${password}' WHERE id = '${user.id}'`)
    throw new Success({ msg: '密码重置成功！' })
  }
  throw new HttpException({ msg: '账号异常，请联系管理员' })
})
export default router
